package com.croke.scratch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;

public class BMap {
	
	private File file;
	private FileInputStream fis = null;
	private FileChannel fc;
	public MappedByteBuffer mb = null;
	private int offset = 0;
	
	public BMap(Path p, int mbSize) {
		
		if (mbSize < 1) {
			throw new IllegalArgumentException("map buffer size must be greater than 0");
		}
		file = p.toFile();
		fis = null;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		fc = fis.getChannel();

		try {
			// try to get some data right off.
			mb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
					mbSize);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int read(byte[] dst, int qty) {
		int noBytes = mb.limit();
		// he wants qty bytes
		
		// what can I give?
		// noBytes - offset is max I can give
		// he wants qty , is this < noBytes - offset?, if so give him the qty he desires.
		// If not, we should go get some more data right away!
		mb.get(dst, offset, noBytes);
		offset += noBytes;
		return(noBytes);
	}
}
